import os
import pathlib

from flask import *

from Service.UPS import *
from multiprocessing import Process

app = Flask(__name__)

'''
{
  "driver": "async",
  "urls": [
      "https://www.baidu.com",
      "https://www.163.com",
      "https://www.sina.com"
  ]
}

'''


@app.route("/prober", methods=["GET"])
def query_task():
    _params = request.args
    _dict = get_database_dict()["tasks"]
    if "task_id" not in _params:
        return jsonify({"code": "500", "message": "Invalid parameter"})
    if _params["task_id"] not in _dict:
        return jsonify({"code": "500", "message": "Task id no does not exist"})
    if "details" in _params and _params["details"]:
        return jsonify({"code": "200", "data": _dict[_params["task_id"]]["urls"]})
    return jsonify({"code": "200", "data": {"ready": _dict[_params["task_id"]]["ready"]}})


@app.route("/prober", methods=["POST"])
def create_task():
    _task = request.json
    if "driver" not in _task or "urls" not in _task:
        return jsonify({"code": "500", "message": "Invalid payload"})
    _task["ready"] = 0
    task_id = add_task(_task)
    return jsonify({"code": "200", "data": {"task_id": task_id}})


def add_task(task):
    _dict = get_database_dict()
    _id = len(_dict["tasks"]) + 1
    _urls_list = copy.deepcopy(task["urls"])
    task["urls"] = []
    for url in _urls_list:
        _url = {
            "url": url,
            "status": "EMPTY"
        }
        task["urls"].append(_url)
    _dict["tasks"][str(_id)] = task
    write_dict_to_database(_dict)
    return _id


def init():
    if pathlib.Path("UPS_tasks.json").is_file():
        Process(target=main, args=()).start()
        return True
    _dict = {
        # the server is closed If the run time does not update in 2 second
        "tasks": {}
    }
    write_dict_to_database(_dict)
    init()


if __name__ == '__main__':
    init()
    app.run(host='0.0.0.0', port=8888, debug=False)
    os.system("python UPS.py")
